import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:me_code_flutter/components/property/property_detail.dart';
import 'package:me_code_flutter/components/user/drawer_user.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'model.dart';

class PropertyList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        drawer: DrawerUser(),
        appBar: AppBar(
          automaticallyImplyLeading: false, // 去除返回按钮
          title: Text('资产'),
          leading: Builder(builder: (BuildContext context) {
            return IconButton(
              icon: Icon(Icons.menu, color: Colors.white, size: 22.0),
              onPressed: () {
                Scaffold.of(context).openDrawer();
              },
              tooltip: MaterialLocalizations.of(context)
                  .openAppDrawerTooltip, //打开抽屉drawer
            );
          }),
          centerTitle: true,
          elevation: 0.0,
        ),
        body: PropertyListHome(),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (context) =>
                    PropertyDetail(item: Post('', '1', '', '', '', '1', ''))));
          },
        ));
  }
}

class PropertyListHome extends StatefulWidget {
  @override
  _PropertyListHomeState createState() => _PropertyListHomeState();
}

class _PropertyListHomeState extends State<PropertyListHome> {
  String totalSum;
  @override
  void initState() {
    super.initState();
  }

  String formatNum(num, {point: 0}) {
    if (num != null) {
      String str = double.parse(num.toString()).toString();
      // 分开截取
      List<String> sub = str.split('.');
      // 处理值
      List val = List.from(sub[0].split(''));
      // 处理点
      List<String> points = List.from(sub[1].split(''));
      //处理分割符
      for (int index = 0, i = val.length - 1; i >= 0; index++, i--) {
        // 除以三没有余数、不等于零并且不等于1 就加个逗号
        if (index % 3 == 0 && index != 0 && i != 1) val[i] = val[i] + ',';
      }
      // 处理小数点
      for (int i = 0; i <= point - points.length; i++) {
        points.add('0');
      }
      //如果大于长度就截取
      if (points.length > point) {
        // 截取数组
        points = points.sublist(0, point);
      }
      // 判断是否有长度
      if (points.length > 0) {
        return '${val.join('')}.${points.join('')}';
      } else {
        return val.join('');
      }
    } else {
      return "0.0";
    }
  }

  Future fetchPosts() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // 获得密码
    final codeResponse = await http.get(
      'https://me.yuanqiao.pw/api/me/getPropertyList.php',
      headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')},
    );
    if (codeResponse.statusCode == 200) {
      final codeResponseBody = json.decode(codeResponse.body);
      if (codeResponseBody['state'] == '3') {
        Navigator.of(context).pushNamedAndRemoveUntil(
          '/login',
          (route) => route == null,
        );
      } else {
        totalSum = codeResponseBody['total'];
        List<Post> posts = codeResponseBody['data']
            .map<Post>((item) => Post.fromJson(item))
            .toList();
        return posts;
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchPosts(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print('data: ${snapshot.data}');
        print('connectionState: ${snapshot.connectionState}');
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Padding(
              padding: EdgeInsets.all(10.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '加载中',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  SizedBox(
                    child: CircularProgressIndicator(strokeWidth: 1.0),
                    height: 20.0,
                    width: 20.0,
                  )
                  // 加载图标
                ],
              ),
            ),
          );
        } else {
          if (snapshot.data.length == 0) {
            return Center(
                child: Container(
              padding: EdgeInsets.only(bottom: 35),
              child: Text('还没有添加数据', style: TextStyle(color: Colors.black38)),
            ));
          }
          // return Container(child: Center(child: Text('fsdfdsfs')));
        }
        // snapshot.data.unshift({});
        return Container(
            padding: EdgeInsets.only(bottom: 16.0),
            child: SingleChildScrollView(
                child: Column(
              children: [
                Container(
                    padding: EdgeInsets.all(26.0),
                    decoration: new BoxDecoration(
                        color: Colors.blue //Color(0xffFF7363) // (0xffF0FDF0),
                        ),
                    child: Center(
                        child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      // mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('总资产：',
                            style:
                                TextStyle(color: Colors.white, fontSize: 18)),
                        Text(formatNum(totalSum),
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 22,
                                fontWeight: FontWeight.w800)),
                      ],
                    ))),
                Column(crossAxisAlignment: CrossAxisAlignment.start,
                    // padding: EdgeInsets.only(bottom: 26.0),
                    children: <Widget>[
                      Container(
                          padding: EdgeInsets.only(left: 12.0),
                          child: Text('资金账户',
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 2,
                                  fontWeight: FontWeight.w800))),
                      Column(
                          children: snapshot.data.map<Widget>((item) {
                        if (item.account_type == '1') {
                          return ListTile(
                            title: Text(item.account_name),
                            subtitle: Text(
                              item.money,
                              style: TextStyle(color: Colors.blue),
                            ),
                            onTap: () {
                              Navigator.push(context, MaterialPageRoute(
                                  //注意传递的参数。goods_list[index]，是吧索引下的item 数据传递了
                                  builder: (context) {
                                return PropertyDetail(item: item);
                              }));
                            },
                          );
                        }
                        return Container();
                      }).toList()),
                      Container(
                          padding: EdgeInsets.only(left: 12.0),
                          child: Text('虚拟账户',
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 2,
                                  fontWeight: FontWeight.w800))),
                      Column(
                          children: snapshot.data.map<Widget>((item) {
                        if (item.account_type == '2') {
                          return ListTile(
                            title: Text(item.account_name),
                            subtitle: Text(
                              item.money,
                              style: TextStyle(color: Colors.blue),
                            ),
                            onTap: () {
                              Navigator.push(context, MaterialPageRoute(
                                  //注意传递的参数。goods_list[index]，是吧索引下的item 数据传递了
                                  builder: (context) {
                                return PropertyDetail(item: item);
                              }));
                            },
                          );
                        }
                        return Container();
                      }).toList()),
                      Container(
                          padding: EdgeInsets.only(left: 12.0),
                          child: Text('借入借出',
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 2,
                                  fontWeight: FontWeight.w800))),
                      Column(
                          children: snapshot.data.map<Widget>((item) {
                        if (item.account_type == '3') {
                          return ListTile(
                            title: Text(item.account_name),
                            subtitle: Text(item.money,
                                style: TextStyle(color: Colors.blue)),
                            onTap: () {
                              Navigator.push(context, MaterialPageRoute(
                                  //注意传递的参数。goods_list[index]，是吧索引下的item 数据传递了
                                  builder: (context) {
                                return PropertyDetail(item: item);
                              }));
                            },
                          );
                        }
                        return Container();
                      }).toList()),
                    ])
              ],
            )));
      },
    );
  }
}
